package com.atguigu.flink.wordcount;

import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 *
 * Created by Smexy on 2023/3/31
 *
 *      模拟无界流，模拟端口，不断发送
 *              安装nc: sudo yum -y install nc
 *
 */
public class Demo3_UnBoundStreamDemo
{
    public static void main(String[] args) throws Exception {

        System.out.println("hahaha...");

        //①创建运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //全程只用一个线程计算
        env.setParallelism(1);

        //②从运行环境中读数据，封装为数据模型
        DataStreamSource<String> ds = env.socketTextStream("hadoop102", 8888);
        //③调用api计算  输入: 一行  输出: (单词,1)
        SingleOutputStreamOperator<Tuple2<String, Integer>> ds2 = ds
            .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>()
            {
                /*
                        Collector<T> out:  输出结果的收集器。
                            调用收集器把想输出的数据输出
                 */
                @Override
                public void flatMap(String line, Collector<Tuple2<String, Integer>> out) throws Exception {

                    String[] words = line.split(" ");
                    for (String word : words) {
                        out.collect(Tuple2.of(word, 1));
                    }
                }
            });
        ds2
            /*
                 当前的数据类型是 Tuple类型，调用  groupBy(int fields), 按照tuple中字段的位置分组。位置索引从0开始！

                 当前的数据类型是 POJO(Bean)类型，调用  groupBy(String fields)， 按照POJO中字段名分组

             */
            .keyBy(new KeySelector<Tuple2<String, Integer>, String>()
            {
                // 输入一个 Tuple2<String, Integer> value，如何获取其中的key
                @Override
                public String getKey(Tuple2<String, Integer> value) throws Exception {
                    return value.f0;
                }
            })
            .sum(1)
            //④输出
            .print();


            //流处理，必须启动环境。批处理不需要
        JobExecutionResult executionResult = env.execute();

        //xxxxxxx

    }
}
